from fastapi import APIRouter, Depends, HTTPException, status, Query, Form, File, UploadFile
from sqlalchemy.orm import Session
from sqlalchemy import desc, asc
from typing import Optional
from database import get_db
from models import User, Work
from schemas import (
    ResponseModel, 
    UserResponse, 
    UserUpdate, 
    WorkResponse, 
    WorkListResponse,
    WorkUpdate,
    WorkCreate,
    PaginationParams,
    EmailVerificationRequest, 
    EmailVerificationConfirm,
    PhoneVerificationRequest, 
    PhoneVerificationConfirm,
    RealNameVerificationRequest, 
    VerificationResponse
)
from auth import get_current_active_user
from utils import cleanup_file, process_image_upload, save_upload_file, generate_filename, get_file_url
import os
from config import settings

router = APIRouter(prefix="/api/user", tags=["用户信息"])

@router.get("/profile", response_model=ResponseModel)
async def get_user_profile(current_user: User = Depends(get_current_active_user)):
    """
    获取用户个人信息
    
    Args:
        current_user: 当前登录用户
    
    Returns:
        ResponseModel: 包含用户信息的响应
    """
    return ResponseModel(
        code=200,
        message="success",
        data={
            "id": current_user.id,
            "username": current_user.username,
            "nickname": current_user.nickname,
            "email": current_user.email,
            "avatar": current_user.avatar,
            "createdAt": current_user.created_at.isoformat()
        }
    )

@router.put("/profile", response_model=ResponseModel)
async def update_user_profile(
    user_update: UserUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    更新用户个人信息
    
    Args:
        user_update: 用户更新数据
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含更新后用户信息的响应
    
    Raises:
        HTTPException: 如果邮箱已被其他用户使用
    """
    # 检查邮箱是否被其他用户使用
    if user_update.email and user_update.email != current_user.email:
        existing_user = db.query(User).filter(
            User.email == user_update.email,
            User.id != current_user.id
        ).first()
        
        if existing_user:
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail="邮箱已被其他用户使用"
            )
    
    # 更新用户信息
    update_data = user_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(current_user, field, value)
    
    db.commit()
    db.refresh(current_user)
    
    return ResponseModel(
        code=200,
        message="更新成功",
        data={
            "id": current_user.id,
            "username": current_user.username,
            "nickname": current_user.nickname,
            "email": current_user.email,
            "avatar": current_user.avatar
        }
    )

@router.get("/works", response_model=ResponseModel)
async def get_user_works(
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(10, ge=1, le=100, description="每页数量"),
    category: Optional[str] = Query(None, description="作品分类"),
    sort: str = Query("latest", description="排序方式: latest/popular/views"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户作品列表
    
    Args:
        page: 页码
        limit: 每页数量
        category: 作品分类过滤
        sort: 排序方式
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含作品列表的响应
    """
    # 构建查询
    query = db.query(Work).filter(Work.user_id == current_user.id)
    
    # 分类过滤
    if category:
        query = query.filter(Work.category == category)
    
    # 排序
    if sort == "popular":
        query = query.order_by(desc(Work.likes))
    elif sort == "views":
        query = query.order_by(desc(Work.views))
    else:  # latest
        query = query.order_by(desc(Work.created_at))
    
    # 获取总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * limit
    works = query.offset(offset).limit(limit).all()
    
    # 转换为响应格式
    works_data = []
    for work in works:
        works_data.append({
            "id": work.id,
            "title": work.title,
            "description": work.description,
            "category": work.category,
            "tags": work.tags or [],
            "thumbnail": work.thumbnail,
            "fileUrl": work.file_url,
            "views": work.views,
            "likes": work.likes,
            "comments": work.comments,
            "createdAt": work.created_at.isoformat()
        })
    
    return ResponseModel(
        code=200,
        message="success",
        data={
            "total": total,
            "page": page,
            "limit": limit,
            "works": works_data
        }
    )

@router.post("/works", response_model=ResponseModel)
async def create_work(
    title: str = Form(..., description="作品标题"),
    description: Optional[str] = Form(None, description="作品描述"),
    category: str = Form(..., description="作品分类"),
    tags: Optional[str] = Form(None, description="标签，逗号分隔"),
    file: UploadFile = File(..., description="作品文件"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    创建新作品
    
    Args:
        title: 作品标题
        description: 作品描述
        category: 作品分类
        tags: 标签字符串
        file: 作品文件
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含作品信息的响应
    
    Raises:
        HTTPException: 如果验证失败
    """
    # 验证分类
    valid_categories = ["image", "video", "music", "text"]
    if category not in valid_categories:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"无效的作品分类，支持的分类: {', '.join(valid_categories)}"
        )
    
    # 处理标签
    tag_list = []
    if tags:
        tag_list = [tag.strip() for tag in tags.split(",") if tag.strip()]
    
    try:
        # 根据分类上传文件
        if category == "image":
            upload_result = await process_image_upload(file, "work")
        else:
            # 其他类型文件的简单上传
            filename = generate_filename(file.filename, category)
            save_dir = os.path.join(settings.upload_dir, "works")
            file_path = await save_upload_file(file, save_dir, filename)
            
            upload_result = {
                "url": get_file_url(file_path),
                "thumbnail": None,
                "size": os.path.getsize(file_path),
                "mime_type": file.content_type,
                "filename": filename
            }
        
        # 创建作品记录
        db_work = Work(
            title=title,
            description=description,
            category=category,
            tags=tag_list,
            file_url=upload_result["url"],
            thumbnail=upload_result.get("thumbnail"),
            file_size=upload_result.get("size"),
            mime_type=upload_result.get("mime_type"),
            user_id=current_user.id
        )
        
        db.add(db_work)
        db.commit()
        db.refresh(db_work)
        
        return ResponseModel(
            code=200,
            message="作品创建成功",
            data={
                "id": db_work.id,
                "title": db_work.title,
                "description": db_work.description,
                "category": db_work.category,
                "tags": db_work.tags or [],
                "thumbnail": db_work.thumbnail,
                "fileUrl": db_work.file_url,
                "views": db_work.views,
                "likes": db_work.likes,
                "comments": db_work.comments,
                "createdAt": db_work.created_at.isoformat()
            }
        )
    
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"作品创建失败: {str(e)}"
        )

@router.put("/works/{work_id}", response_model=ResponseModel)
async def update_work(
    work_id: int,
    work_update: WorkUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    更新作品信息
    
    Args:
        work_id: 作品ID
        work_update: 作品更新数据
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含更新后作品信息的响应
    
    Raises:
        HTTPException: 如果作品不存在或无权限
    """
    # 查询作品
    work = db.query(Work).filter(
        Work.id == work_id,
        Work.user_id == current_user.id
    ).first()
    
    if not work:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="作品不存在或无权限访问"
        )
    
    # 更新作品信息
    update_data = work_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(work, field, value)
    
    db.commit()
    db.refresh(work)
    
    return ResponseModel(
        code=200,
        message="作品更新成功",
        data={
            "id": work.id,
            "title": work.title,
            "description": work.description,
            "category": work.category,
            "tags": work.tags or [],
            "thumbnail": work.thumbnail,
            "fileUrl": work.file_url,
            "views": work.views,
            "likes": work.likes,
            "comments": work.comments,
            "createdAt": work.created_at.isoformat(),
            "updatedAt": work.updated_at.isoformat() if work.updated_at else None
        }
    )

@router.delete("/works/{work_id}", response_model=ResponseModel)
async def delete_work(
    work_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    删除作品
    
    Args:
        work_id: 作品ID
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 删除成功响应
    
    Raises:
        HTTPException: 如果作品不存在或无权限
    """
    # 查询作品
    work = db.query(Work).filter(
        Work.id == work_id,
        Work.user_id == current_user.id
    ).first()
    
    if not work:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="作品不存在或无权限访问"
        )
    
    # 删除相关文件
    if work.file_url:
        # 构建文件路径
        file_path = work.file_url.replace("/uploads/", "")
        full_file_path = os.path.join(settings.upload_dir, file_path)
        cleanup_file(full_file_path)
    
    if work.thumbnail:
        # 删除缩略图
        thumbnail_path = work.thumbnail.replace("/uploads/", "")
        full_thumbnail_path = os.path.join(settings.upload_dir, thumbnail_path)
        cleanup_file(full_thumbnail_path)
    
    # 删除数据库记录
    db.delete(work)
    db.commit()
    
    return ResponseModel(
        code=200,
        message="作品删除成功",
        data=None
    )

@router.get("/stats", response_model=ResponseModel)
async def get_user_stats(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户统计信息
    
    Args:
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含用户统计信息的响应
    """
    # 统计作品数量
    total_works = db.query(Work).filter(Work.user_id == current_user.id).count()
    
    # 统计各分类作品数量
    image_count = db.query(Work).filter(
        Work.user_id == current_user.id,
        Work.category == "image"
    ).count()
    
    video_count = db.query(Work).filter(
        Work.user_id == current_user.id,
        Work.category == "video"
    ).count()
    
    music_count = db.query(Work).filter(
        Work.user_id == current_user.id,
        Work.category == "music"
    ).count()
    
    text_count = db.query(Work).filter(
        Work.user_id == current_user.id,
        Work.category == "text"
    ).count()
    
    # 统计总浏览量和点赞数
    works = db.query(Work).filter(Work.user_id == current_user.id).all()
    total_views = sum(work.views for work in works)
    total_likes = sum(work.likes for work in works)
    
    return ResponseModel(
        code=200,
        message="success",
        data={
            "totalWorks": total_works,
            "totalViews": total_views,
            "totalLikes": total_likes,
            "categoryStats": {
                "image": image_count,
                "video": video_count,
                "music": music_count,
                "text": text_count
            }
        }
    )

# 认证相关接口
@router.post("/email/send-verification", response_model=VerificationResponse)
async def send_email_verification(
    request: EmailVerificationRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    发送邮箱验证码
    """
    try:
        # 检查邮箱是否已被其他用户使用
        existing_user = db.query(User).filter(
            User.email == request.email,
            User.id != current_user.id
        ).first()
        
        if existing_user:
            raise HTTPException(
                status_code=400,
                detail="该邮箱已被其他用户使用"
            )
        
        # 生成6位验证码
        import random
        verification_code = str(random.randint(100000, 999999))
        
        # 这里应该发送邮件，暂时模拟
        # TODO: 集成邮件服务
        print(f"发送验证码到 {request.email}: {verification_code}")
        
        # 将验证码存储到缓存或数据库（这里简化处理）
        # TODO: 使用Redis存储验证码，设置5分钟过期时间
        
        return VerificationResponse(
            success=True,
            message="验证码已发送到您的邮箱"
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail="发送验证码失败")

@router.post("/email/verify", response_model=VerificationResponse)
async def verify_email(
    request: EmailVerificationConfirm,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    验证邮箱
    """
    try:
        # TODO: 从缓存中验证验证码
        # 这里简化处理，假设验证码正确
        if request.code != "123456":  # 临时验证码
            raise HTTPException(
                status_code=400,
                detail="验证码错误或已过期"
            )
        
        # 更新用户邮箱和验证状态
        current_user.email = request.email
        current_user.email_verified = True
        db.commit()
        
        return VerificationResponse(
            success=True,
            message="邮箱验证成功",
            verified=True
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail="邮箱验证失败")

@router.post("/phone/send-verification", response_model=VerificationResponse)
async def send_phone_verification(
    request: PhoneVerificationRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    发送手机验证码
    """
    try:
        # 检查手机号是否已被其他用户使用
        existing_user = db.query(User).filter(
            User.phone == request.phone,
            User.id != current_user.id
        ).first()
        
        if existing_user:
            raise HTTPException(
                status_code=400,
                detail="该手机号已被其他用户使用"
            )
        
        # 生成6位验证码
        import random
        verification_code = str(random.randint(100000, 999999))
        
        # 这里应该发送短信，暂时模拟
        # TODO: 集成短信服务
        print(f"发送验证码到 {request.phone}: {verification_code}")
        
        # 将验证码存储到缓存或数据库（这里简化处理）
        # TODO: 使用Redis存储验证码，设置5分钟过期时间
        
        return VerificationResponse(
            success=True,
            message="验证码已发送到您的手机"
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail="发送验证码失败")

@router.post("/phone/verify", response_model=VerificationResponse)
async def verify_phone(
    request: PhoneVerificationConfirm,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    验证手机号
    """
    try:
        # TODO: 从缓存中验证验证码
        # 这里简化处理，假设验证码正确
        if request.code != "123456":  # 临时验证码
            raise HTTPException(
                status_code=400,
                detail="验证码错误或已过期"
            )
        
        # 更新用户手机号和验证状态
        current_user.phone = request.phone
        current_user.phone_verified = True
        db.commit()
        
        return VerificationResponse(
            success=True,
            message="手机号验证成功",
            verified=True
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail="手机号验证失败")

@router.post("/real-name/verify", response_model=VerificationResponse)
async def verify_real_name(
    request: RealNameVerificationRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    实名认证
    """
    try:
        # 检查身份证号是否已被其他用户使用
        existing_user = db.query(User).filter(
            User.id_card == request.id_card,
            User.id != current_user.id
        ).first()
        
        if existing_user:
            raise HTTPException(
                status_code=400,
                detail="该身份证号已被其他用户使用"
            )
        
        # TODO: 调用第三方实名认证接口
        # 这里简化处理，假设认证成功
        
        # 更新用户实名信息和验证状态
        current_user.real_name = request.real_name
        current_user.id_card = request.id_card
        current_user.real_name_verified = True
        db.commit()
        
        return VerificationResponse(
            success=True,
            message="实名认证成功",
            verified=True
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail="实名认证失败")